package com.example.words;

import android.content.Context;

import androidx.annotation.NonNull;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import androidx.room.migration.Migration;
import androidx.sqlite.db.SupportSQLiteDatabase;

/**
 * 改进采用singleton单实例，因为多个实例化比较耗费资源
 */
//@Database(entities = {Word.class},version = 1,exportSchema = false)
//@Database(entities = {Word.class},version = 2,exportSchema = false)
//@Database(entities = {Word.class},version = 3,exportSchema = false)
//@Database(entities = {Word.class},version = 4,exportSchema = false)
@Database(entities = {Word.class},version = 5,exportSchema = false)
public abstract class WordDatabase extends RoomDatabase {
    private static WordDatabase INSTANCE;
    //synchronized同步，多个线程采用排队机制
    static synchronized WordDatabase getDatabase(Context context){
        if(INSTANCE == null){
//            INSTANCE = Room.databaseBuilder(context.getApplicationContext(),WordDatabase.class,"word_database")
//                    .build();

            INSTANCE = Room.databaseBuilder(context.getApplicationContext(),WordDatabase.class,"word_database")
                    //.fallbackToDestructiveMigration()破坏性迁移
                    //.addMigrations(MIGRATION_2_3)
                    //.addMigrations(MIGRATION_3_4)
                    .addMigrations(MIGRATION_4_5)
                    .build();
        }
        return INSTANCE;
    }
    public abstract WordDao getWordDao();

    //迁移策略
    static final Migration MIGRATION_2_3 = new Migration(2,3) {
        @Override
        public void migrate(@NonNull SupportSQLiteDatabase database) {
            database.execSQL("ALTER TABLE Word ADD COLUMN bar_data INTEGER NOT NULL DEFAULT 1");
        }
    };

    //迁移策略
    static final Migration MIGRATION_3_4 = new Migration(3,4) {
        @Override
        public void migrate(@NonNull SupportSQLiteDatabase database) {
            database.execSQL("CREATE TABLE Word_temp (id INTEGER PRIMARY KEY NOT NULL,英文名 TEXT, 中文名 TEXT )");
            database.execSQL("INSERT INTO Word_temp (id,英文名, 中文名)" + "SELECT id,英文名,中文名 FROM Word");
            database.execSQL("DROP TABLE Word");
            database.execSQL("ALTER TABLE Word_temp RENAME to Word");
        }
    };

    //迁移策略
    private static final Migration MIGRATION_4_5 = new Migration(4,5) {
        @Override
        public void migrate(@NonNull SupportSQLiteDatabase database) {
            database.execSQL("ALTER TABLE Word ADD COLUMN chinese_invisible INTEGER NOT NULL DEFAULT 0");
        }
    };
}
